package org.budo.mongo.jdbc.driver.statement.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.mongo.jdbc.driver.executor.MongoStatementExecutor;
import org.budo.mongo.jdbc.driver.statement.AbstractMongoStatement;
import org.budo.mongo.jdbc.driver.statement.StatementDocument;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.lang.util.StringUtil;

import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * @author lmw
 */
@Setter
@Accessors(chain = true)
public class SHOW_CREATE_TABLE extends AbstractMongoStatement {
    private static final String TABLE = "Table";

    private static final String CREATE_TABLE = "Create Table";

    private String tableName;

    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        MongoStatementExecutor statementExecutor = this.statementExecutor(preparedStatement);

        // 没结果
        Iterator<?> iterator = statementExecutor.find(this.tableName, new StatementDocument().limit(1));
        if (!iterator.hasNext()) {
            Map<String, String> valueMap = MapUtil.stringMap(TABLE, this.tableName, //
                    CREATE_TABLE, "EMPTY TABLE " + this.tableName);
            ResultSet resultSet = new MapArrayResultSet(new String[] { TABLE, CREATE_TABLE }, new Map[] { valueMap });
            ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
            return;
        }

        // 先把第一行读出来，得到列信息，然后暂存第一行
        Map<?, ?> next = (Map<?, ?>) iterator.next();
        String[] columnNames = next.keySet().toArray(new String[next.size()]);

        Map<String, String> valueMap = MapUtil.stringMap(TABLE, this.tableName, //
                CREATE_TABLE, "CREATE TABLE " + this.tableName + " (\n " + StringUtil.join(columnNames, ",\n", "\t", "") + "\n ) ");

        ResultSet resultSet = new MapArrayResultSet(new String[] { TABLE, CREATE_TABLE }, new Map[] { valueMap });
        ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}